<?php

namespace app\boss\service;
use think\Cookie;
use think\Request;

/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/11/20
 * Time: 15:09
 */
class User
{
    /**
     * 判断用户是否登录，并返回token
     * @return bool
     */
    public function isLogin($appid,$authUrl){
        $oauth_user =  $this->OAuth2Login($appid,$authUrl);
        $oauth_user = json_decode($oauth_user);
        return $oauth_user;
    }
    /**
     * 获取用户标识，并返回
     * @param $appid
     * @param $authUrl
     * @return bool|mixed
     */
    private function  OAuth2Login($appid,$authUrl){
        if(Request::instance()->get('code') == null){
            $authUrl = urlencode($authUrl);
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$authUrl."&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
            header("Location:".$url);
            exit();
        }else{
            $url = "https://minitest.17jxyx.com/api/v1/token/boss";
            $code = Request::instance()->get('code');
            $params = [
                "code"=>$code
            ];
            $userInfo = curl_post($url,$header=0,$params);//请求用户详情
            $result =  $this->handelToken($userInfo);
            return $result;
        }
    }
    /**
     * 处理token
     * @param $data
     * @return bool
     */
    private function handelToken($data){
        $info = json_decode($data);
       // var_export($info);
        if ($info->error_code == 0){
            Cookie::set('BOSS_TT',$info->token,$info->expire_in);
            //请求用户数据
            $url ="https://minitest.17jxyx.com/api/v1/enterprise/user";
            $userInfo = curl_get($url,$header=$info->token);//请求用户详情
            return $userInfo;
        }else{
            return $data;
        }
    }
}